package com.tanhua.dubbo.api;

import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.Video;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.util.StringUtils;

import java.util.List;

@DubboService
public class CommentApiImpl implements CommentApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 分页查询评论列表
     *
     * @param movementId
     * @param commentType
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public List<Comment> findComments(String movementId, CommentType commentType, Integer page, Integer pagesize) {
        //构造查询条件
        Query query = Query.query
                (Criteria.where("publishId")
                        //发布人id和传过来的动态编号一致
                        .is(new ObjectId(movementId))
                        .and("commentType")
                        .is(commentType.getType()))
                .skip((page - 1) * pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        //查询并返回
        return mongoTemplate.find(query, Comment.class);
    }

    /**
     * 保存互动状态，返回数量
     *
     * @param comment1
     * @return
     */
    @Override
    public Integer saveComments(Comment comment1) {
        //1.查询动态详情
        Movement movement = mongoTemplate.findById(comment1.getPublishId(), Movement.class);
        //2.向comment对象设置被评论人
        if (movement != null) {
            //movement的UserId是发布人id
            comment1.setPublishUserId(movement.getUserId());
        }
        //3.保存到数据库
        mongoTemplate.save(comment1);
        //4.更新动态表中对应的字段  发布人的id对应动态详情表中的id字段
        Query query = Query.query(Criteria.where("id").is(comment1.getPublishId()));
        Update update = new Update();
        if (comment1.getCommentType() == CommentType.LIKE.getType()) {
            update.inc("likeCount", 1);
        } else if (comment1.getCommentType() == CommentType.COMMENT.getType()) {
            update.inc("commentCount", 1);
        } else {
            update.inc("loveCount", 1);
        }
        //5,设置更新参数
        //调用底层的return this; 返回当前数据
        FindAndModifyOptions options = new FindAndModifyOptions();
        //获取更新后的数据
        options.returnNew(true);
        Movement andModify = mongoTemplate.findAndModify(query, update, options, Movement.class);
        //6、获取最新的评论数量，并返回
        return andModify.statisCount(comment1.getCommentType());
    }

    /**
     * 删除互动状态，返回数量
     *
     * @param comment
     * @return
     */
    @Override
    public Integer delete(Comment comment) {
        //1.删除comment表数据
        Criteria criteria = Criteria.where("publishId").is(comment.getPublishId())
                .and("userId").is(comment.getUserId())
                .and("commentType").is(comment.getCommentType());
        Query query = Query.query(criteria);
        mongoTemplate.remove(query, Comment.class);
        //2.修改数据表中对应的数据
        Query movementQuery = Query.query(Criteria.where("id").is(comment.getPublishId()));
        Update update = new Update();
        if (comment.getCommentType() == CommentType.LIKE.getType()) {
            update.inc("likeCount", -1);
        } else if (comment.getCommentType() == CommentType.COMMENT.getType()) {
            update.inc("commentCount", -1);
        } else {
            update.inc("loveCount", -1);
        }
        //3.设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true);
        Movement modify = mongoTemplate.findAndModify(movementQuery, update, options, Movement.class);
        //4、获取最新的评论数量，并返回
        return modify.statisCount(comment.getCommentType());
    }

    /**
     * 是否点赞
     *
     * @param movementId
     * @param userId
     * @param commentType
     * @return
     */
    @Override
    public boolean like(String movementId, Long userId, CommentType commentType) {
        Criteria criteria = Criteria.where("publishId").is(new ObjectId(movementId))
                .and("userId").is(userId)
                .and("commentType").is(commentType.getType());
        Query query = Query.query(criteria);
        //返回是否包含这条数据
        return mongoTemplate.exists(query, Comment.class);
    }

    /**
     * 是否喜欢
     *
     * @param movementId
     * @param userId
     * @param commentType
     * @return
     */
    @Override
    public boolean isLove(String movementId, Long userId, CommentType commentType) {
        Criteria criteria = Criteria.where("publishId").is(new ObjectId(movementId))
                .and("userId").is(userId)
                .and("commentType").is(commentType);
        Query query = Query.query(criteria);
        //返回是否包含这条数据
        return mongoTemplate.exists(query, Comment.class);
    }

    /**
     * 点赞后返回评论点赞数
     *
     * @return
     */
    @Override
    public Integer saveLike(Comment comment) {
        //1.保存comment到数据库
        mongoTemplate.save(comment);
        //2.更新动态表中对应的字段
        Query query = Query.query(Criteria.where("id").is(comment.getPublishId()));
        Update update = new Update();
        update.inc("likeCount");
        //3.设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        //获取更新后的数据
        options.returnNew(true);
        Comment modify = mongoTemplate.findAndModify(query, update, Comment.class);
        //4、获取最新的评论数量，并返回
        return modify.statisCount(comment.getCommentType());
    }

    /**
     * 取消点赞后返回点赞数
     *
     * @param comment
     * @return
     */
    @Override
    public Integer deleteLike(Comment comment) {
        //1.删除数据库中对应的数据
        Criteria criteria = Criteria.where("id").is(comment.getPublishId())
                .and("publishUserId").is(comment.getPublishUserId())
                .and("commentType").is(comment.getCommentType());
        Query query = Query.query(criteria);
        mongoTemplate.remove(query);
        //2.修改对应字段的点赞数量
        Query CommentQuery = Query.query(Criteria.where("userId").is(comment.getUserId()));
        Update update = new Update();
        update.inc("likeCount", -1);
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true);
        Comment modify = mongoTemplate.findAndModify(CommentQuery, update, Comment.class);
        //3.返回修改后的点赞数量
        return modify.statisCount(comment.getCommentType());
    }

    /**
     * 查询单条评论数据
     *
     * @param id
     * @return
     */
    @Override
    public Comment findById(String id) {
        Comment comment = mongoTemplate.findById(id, Comment.class);
        return comment;
    }


    @Override
    public boolean common(String movementId, Long userId, CommentType commentType) {
        Criteria criteria = Criteria.where("publishId").is(new ObjectId(movementId))
                .and("userId").is(userId)
                .and("commentType").is(commentType);
        Query query = Query.query(criteria);
        //返回是否包含这条数据
        return mongoTemplate.exists(query, Comment.class);

    }

    /**
     * 构造条件获取每个被评论id与当前登录id相等的互动数据
     *
     * @param userId
     * @param page
     * @param pagesize
     * @param commentType
     * @return
     */
    @Override
    public List<Comment> likes(Long userId, Integer page, Integer pagesize, CommentType commentType) {
        Criteria criteria = Criteria.where("publishUserId").is(userId)
                .and("commentType").is(commentType.getType());
        Query query = Query.query(criteria).skip((page - 1) * pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        return mongoTemplate.find(query, Comment.class);
    }

    /**
     * 视频点赞保存
     *
     * @param comment
     */
    @Override
    public void saveVideo(Comment comment) {
        //1.给数据赋值被评论人 和
        Video video = mongoTemplate.findById(comment.getPublishId(), Video.class);
        if (!StringUtils.isEmpty(video)) {
            comment.setPublishUserId(video.getUserId());
        }
        //2.调用方法保存
        mongoTemplate.save(comment);
        //3.更新video表中的字段
        Query query = Query.query(Criteria.where("userId").is(comment.getPublishUserId()));
        Update update = new Update();
        if (comment.getCommentType() == CommentType.LIKE.getType()) {
            update.inc("likeCount");
        } else if (comment.getCommentType() == CommentType.LOVE.getType()) {
            update.inc("loveCount");
        } else {
            update.inc("commentCount");
        }
        //4.调用方法更新
        mongoTemplate.updateFirst(query, update, Video.class);
    }

    /**
     * 删除视频点赞
     * @param comment
     */
    @Override
    public void remove(Comment comment) {
        //1.构造条件删除数据
        Criteria criteria = Criteria.where("publishId").is(comment.getPublishId())
                .and("userId").is(comment.getUserId())
                .and("commentType").is(comment.getCommentType());
        Query query = Query.query(criteria);
        mongoTemplate.remove(query,Comment.class);
        //2.修改video表中的字段
        Query videoQuery = Query.query(Criteria.where("id").is(comment.getPublishId()));
        Update update = new Update();
        if (comment.getCommentType() == CommentType.LIKE.getType()) {
            update.inc("likeCount", -1);
        } else if (comment.getCommentType() == CommentType.LOVE.getType()) {
            update.inc("loveCount", -1);
        } else {
            update.inc("commentCount", -1);
        }
        //3.调用方法更新
        mongoTemplate.updateFirst(videoQuery, update, Video.class);
    }
}
